package com.zh.note.leetcode.backtracking;

import java.util.*;

/**
 * 491. 递增子序列
 * 输入：nums = [4,6,7,7]
 * 输出：[[4,6],[4,6,7],[4,6,7,7],[4,7],[4,7,7],[6,7],[6,7,7],[7,7]]
 */
public class LC_491_findSubsequences {

    public List<List<Integer>> findSubsequences(int[] nums) {

        List<List<Integer>> res = new ArrayList<>();
        Deque<Integer> path = new LinkedList<>();

        dfs(nums, 0, path, res);
        return res;
    }

    private void dfs(int[] nums, int startIndex, Deque<Integer> path, List<List<Integer>> res) {
        //收集结果
        if (path.size() > 1) {
            res.add(new ArrayList<>(path));
        }
        //终止条件
        if (startIndex >= nums.length) {
            return;
        }
        Set<Integer> used = new HashSet<>(); // 使用set来对本层元素进行去重
        for (int i = startIndex; i < nums.length; i++) {
            if (!path.isEmpty() && nums[i] < path.getLast() || used.contains(nums[i])) {
                continue;
            }
            used.add(nums[i]);// 记录这个元素在本层用过了，本层后面不能再用了
            path.addLast(nums[i]);
            dfs(nums, i + 1, path, res);
            path.removeLast();
        }
    }

}



